package com.sptpc.demo1.controller;

import com.sptpc.demo1.controller.requests.ModifyDrinkRequest;
import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j  //日志
@RestController
@RequestMapping("/category")
public class CategoryController{

    @Autowired //在合适的地方自动实例化对象；
    private ICategoryService categoryService;

    @GetMapping("/")
    public List<Category> getAll(){
        List<Category> results=categoryService.getAllCategory();
        return results;
    }
    /**
     * 新增
     * post  /drink/{"name": "奶茶","price": "8.00"}
     * 1. 直接使用model类接受用户参数
     * 2. 编写一个TO类专门负责传值
     */
    @PostMapping("/")
    public Category addNewDrink(@RequestBody @Valid Category category, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        }else {
            log.info("创建新饮品: {}", category);
            categoryService.addNewCategory(category);
            return category;
        }
    }

    /**
     * 修改
     * put /drink/{"id": 1, "name": "新奶茶", "price": "10.0"}
     */
    @PutMapping("/")
    public Category modifyDrink(@RequestBody ModifyDrinkRequest request){
        log.info("要修改的饮品: {}",request);
        // 后期使用数据库update
        //1. 先通过id查询出对应的数据信息
        Category category=categoryService.getCategoryById(request.getId());
        //2. 复制前端要修改的属性(将前端传递的值覆盖个drink)
        BeanUtils.copyProperties(request,category);
        //3. 更新数据库
        categoryService.updateCategory(category);
        return category;
    }


    /**
     * 删除
     * delete /drink/1
     */
    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id){
        log.info("要删除的饮品id: {}",id);
        categoryService.delCategory(id);
        //后期使用数据库
        return "删除成功";
    }
}
